/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hvtt.web.controller;

import com.hvtt.web.connection.Command;
import com.hvtt.web.connection.WEBConnection;
import com.hvtt.web.connection.WEBParamCollection;
import com.hvtt.web.models.Sys_UserModel;
import com.hvtt.web.models.Sys_nguoidung;
import com.hvtt.web.utilities.Utilities;
import java.io.IOException;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Administrator
 */
@ManagedBean
@SessionScoped
public class Sys_NguoiDungController implements Serializable{
    private WEBConnection DAL=WEBConnection.getInstance();
    
    private Sys_nguoidung item =new Sys_nguoidung();
    
    private String nhapLaiMatkhau="";
    
    
    public String getNhapLaiMatKhau()
    {
        return nhapLaiMatkhau;
    }
    public void setNhapLaiMatKhau(String nhapLaiMatKhau)
    {
        this.nhapLaiMatkhau=nhapLaiMatKhau;
    }
   
    
   
    
  
     
    public Sys_nguoidung getItem()
    {
        return item;
    }
    public void setItem(Sys_nguoidung item)
    {
        this.item=item;
    }
    
    
    public List<Sys_nguoidung> findAllUsers() throws SQLException
    {
        List<Sys_nguoidung>lst=new ArrayList();
        lst=DAL.executeQuery("Select*from users_report order by users_report.IsCP asc",Sys_nguoidung.class );
        return lst;
    }
    
    
    
    
   private boolean isValidEmailAddress(String email) {
        boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}
    
    
    private String validateFields() throws SQLException {
        String str="";
        if (StringUtils.isBlank(this.getItem().getUserID()))
        {
            str= "  + UserID: không thể rổng<br/>";
        }
       
       if(this.item.getId()<=0)
       {
        
            if (StringUtils.isBlank(this.getItem().getPassword()))
            {
                str+="  + Mật khẩu: Không thể rổng<br/>";
            }
            if (this.getItem().getPassword().trim() == null ? this.getNhapLaiMatKhau().trim() != null : !this.getItem().getPassword().trim().equals(this.getNhapLaiMatKhau().trim()))
            {
                str+="  + Nhập lại mật khẩu: Không khớp với mật khẩu ban đầu<br/>";
            }
       }
        
        if("".equals(str.trim()))
            return "";
        return "<b style='color:red;'>" + str + "</b>";
    }
    
    
     public void btnNew_Click(ActionEvent event) throws IOException{
         this.item.Reset();
         String str=FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("loai").toString();
         if("1".equals(str))
         FacesContext.getCurrentInstance().getExternalContext().redirect("/tao-tai-khoan-admin.html");
         else
             FacesContext.getCurrentInstance().getExternalContext().redirect("/tao-tai-khoan-cp.html");
         
     }
     public void btnCancel_Click(ActionEvent event) throws IOException{
         this.item.Reset();
         
         FacesContext.getCurrentInstance().getExternalContext().redirect("/danh-sach-tai-khoan.html");
     }
    public void btnSave_Click(ActionEvent event) throws IOException, SQLException {
        String result = this.validateFields();
        if (!result.isEmpty()) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status",result);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            RequestContext.getCurrentInstance().execute("update=\"growl\"");
            return;
        }
        
       
          try   
          {
              
              this.getItem().setRight(
                 FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("right").toString()
                 );
              this.getItem().setIsGame1(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("game1").toString())
                 );
             this.getItem().setIsGame2(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("game2").toString())
                 );
             this.getItem().setIsGame3(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("game3").toString())
                 );
              this.getItem().setEditInfo(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("editinfo").toString())
                 );
               this.getItem().setThongKeTK(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("thongketk").toString())
                 );
                this.getItem().setTkDoanhThu(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("tkdoanhthu").toString())
                 );
                
                
                 this.getItem().settKNapTien(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TKNapTien").toString())
                 );
                  this.getItem().setTongCashOut(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TongCashOut").toString())
                 );
                   this.getItem().setThongKeDoanhThu(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ThongKeDoanhThu").toString())
                 );
                     this.getItem().setThongKeDoanhThuBit(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ThongKeDoanhThuBit").toString())
                 );
                  this.getItem().setThongKeDoanhThuBac(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ThongKeDoanhThuBac").toString())
                 );
                   this.getItem().setThongKeKhac(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ThongKeKhac").toString())
                 );
                 this.getItem().setTongBit(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TongBit").toString())
                 );
                  this.getItem().setTongBac(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TongBac").toString())
                 );
                 this.getItem().setEpay(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Epay").toString())
                 );
                 this.getItem().setNganLuong(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("NganLuong").toString())
                 );
                 this.getItem().setDoanhThu(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("DoanhThu").toString())
                 );
                this.getItem().setThongKeTheoGame(
                      Boolean.parseBoolean(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ThongKeTheoGame").toString())
                 );
            WEBParamCollection Params=new WEBParamCollection();
            Params.add(this.item.getId());
            Params.add(this.item.getUserID());
            Params.add(this.item.getPassword());
            Params.add(this.item.isIsAdmin());
            Params.add(this.item.isIsCP());
            Params.add(this.item.isIsGame1());
            Params.add(this.item.isIsGame2());
            Params.add(this.item.isIsGame3()); 
            Params.add(this.item.getCpid());
            Params.add(this.item.getCpName());
            Params.add(this.item.isEditInfo());
            Params.add(this.item.isThongKeTK());
            Params.add(this.item.isTkDoanhThu());
            
            Params.add(this.item.getDescr());
            
            Params.add(this.item.istKNapTien());
            Params.add(this.item.isTongCashOut());
            Params.add(this.item.isThongKeDoanhThu());
            Params.add(this.item.isThongKeDoanhThuBit());
            Params.add(this.item.isThongKeDoanhThuBac());
            Params.add(this.item.isThongKeKhac());
            Params.add(this.item.isTongBit());
            Params.add(this.item.isTongBac());
            Params.add(this.item.isEpay());
            Params.add(this.item.isNganLuong());
            Params.add(this.item.isDoanhThu());
            Params.add(this.item.isThongKeTheoGame());
            DAL.executeUpdate("{call proc_user_report_inser_update(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}", Command.sqlText, Params);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/danh-sach-tai-khoan.html");
            
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
     public void btnUpdate_Click(ActionEvent event) throws IOException, SQLException {
         this.getItem().setId(
                 Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id").toString())
                 );
       
          try   
          {
           WEBParamCollection Params=new WEBParamCollection();
           Params.add(this.item.getId());
           List<Sys_nguoidung> lst=DAL.executeQuery("Select*from users_report where users_report.ID=?", Command.sqlText, Params, Sys_nguoidung.class);
           if(lst.size()>0)
               this.setItem(lst.get(0));
                   
             
           if(this.getItem().isIsAdmin())
                FacesContext.getCurrentInstance().getExternalContext().redirect("/tao-tai-khoan-admin.html");
           else
               FacesContext.getCurrentInstance().getExternalContext().redirect("/tao-tai-khoan-cp.html");
            
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
    public void btnDelete_Click(ActionEvent event) throws IOException, SQLException {
         this.getItem().setId(
                 Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id").toString())
                 );
       
          try   
          {
           WEBParamCollection Params=new WEBParamCollection();
           Params.add(this.item.getId());
           DAL.executeUpdate("delete from users_report where users_report.ID=?", Command.sqlText, Params);
           
            FacesContext.getCurrentInstance().getExternalContext().redirect("/danh-sach-tai-khoan.html");
            
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
    
    
    public void btnCapNhatTrangThai_Click(ActionEvent event) throws IOException, SQLException {
        String str=String.valueOf(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TrangThai").toString());
                 
       
          try   
          {
           
           String[]MUsers=str.split(",");
           if(MUsers!=null && MUsers.length>0)
           {
               for(String s:MUsers)
               {
                   String[]M=s.split("_");
                   if(M!=null && M.length==2)
                   {
                       WEBParamCollection Params=WEBParamCollection.getInstance();
                       Params.add(Boolean.parseBoolean(M[1]));
                       Params.add(M[0]);
                       
                       DAL.executeUpdate("Update users_report set users_report.TrangThai=? where users_report.ID=?", Command.sqlText, Params);
                   }
               }
           }
           
           
           
            FacesContext.getCurrentInstance().getExternalContext().redirect("/danh-sach-tai-khoan.html");
            
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
    
     
    public void DangNhap(ActionEvent event) throws SQLException {
       
          String Ma=String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("Ma"));
          String MatKhau=String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("MatKhau"));
         WEBParamCollection Params=new WEBParamCollection();
            Params.add(Ma);
            Params.add(MatKhau);
           
            List<Sys_nguoidung> lst=new ArrayList<>();
        try {
            lst = DAL.executeQuery("select*from users_report where users_report.UserID=? and users_report.Password=MD5(?)", Command.sqlText, Params,Sys_nguoidung.class);
        } catch (SQLException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
            if(lst==null || lst.size()<=0)
            {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status","<b style='color:red'>" + Utilities.getLanguages("TaiKhoanKhongHopLe")+"</b>");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return ;
            }
            
            if("".equals(lst.get(0).getUserID().trim()))
            {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status","<b style='color:red'>" + Utilities.getLanguages("TaiKhoanKhongHopLe")+"</b>");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return ;
            }
            if(!lst.get(0).isTrangThai())
            {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status","<b style='color:red'>Tài khoản đã bị vô hiệu hóa.</b>");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return ;
            }
            
              Sys_UserModel objUser=new Sys_UserModel();
              objUser.setUserID(lst.get(0).getUserID());
              objUser.setIsAdmin(lst.get(0).isIsAdmin());
              objUser.setIsCP(lst.get(0).isIsCP());
              objUser.setIsGame1(lst.get(0).isIsGame1());
              objUser.setIsGame2(lst.get(0).isIsGame2());
              objUser.setIsGame3(lst.get(0).isIsGame3());
              objUser.setEditInfo(lst.get(0).isEditInfo());
              objUser.setThongKeTK(lst.get(0).isThongKeTK());
              objUser.setTkDoanhThu(lst.get(0).isTkDoanhThu());
              objUser.setDoanhThu(lst.get(0).isDoanhThu());
              
              
                      
              FacesContext context = FacesContext.getCurrentInstance();  
        
            HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();  
            HttpSession httpSession = request.getSession(false);  
            httpSession.setAttribute(Utilities.getSS_USER(), objUser);
        try {              
            FacesContext.getCurrentInstance().getExternalContext().redirect("/trang-chu.html");
        } catch (IOException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void ThayDoiMatKhau_Click(ActionEvent event) throws SQLException {
       
         
          String MatKhau=String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("MatKhau"));
          String MatKhauMoi=String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("MatKhauMoi"));
          String NhapLaiMatKhau=String.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("NhapLaiMatKhauMoi"));
          
         WEBParamCollection Params=new WEBParamCollection();
            Params.add(this.findObjUser().getUserID());
            Params.add(MatKhau);
           
            List<Sys_nguoidung> lst=new ArrayList<>();
        try {
            lst = DAL.executeQuery("select*from users_report where users_report.UserID=? and users_report.Password=MD5(?)", Command.sqlText, Params,Sys_nguoidung.class);
        } catch (SQLException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
            if(lst==null || lst.size()<=0)
            {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status","<b style='color:red'>Tài khoản không hợp lệ</b>");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return ;
            }
            
            if("".equals(lst.get(0).getUserID().trim()))
            {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status","<b style='color:red'>Tài khoản không hợp lệ</b>");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return ;
            }
            
           if(MatKhauMoi.trim() == null ? NhapLaiMatKhau.trim() != null : !MatKhauMoi.trim().equals(NhapLaiMatKhau.trim()))
           {
               FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status","<b style='color:red'>Mật khẩu và nhập lại mật khẩu không trùng nhau.</b>");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return ;
           }
              
           
           WEBParamCollection Params1=new WEBParamCollection();
           Params1.add(MatKhauMoi);
           Params1.add(this.findObjUser().getUserID());
           
           DAL.executeUpdate("update users_report set users_report.Password=MD5(?) where users_report.UserID=?", Command.sqlText, Params1);
           FacesContext context = FacesContext.getCurrentInstance();  
        
          
        try {              
            FacesContext.getCurrentInstance().getExternalContext().redirect("/dang-nhap.html");
        } catch (IOException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void onPageLoad_DangXuat()
    {
            FacesContext context = FacesContext.getCurrentInstance();  
            HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();  
            HttpSession httpSession = request.getSession(false);  
            httpSession.removeAttribute(Utilities.getSS_USER());
         try {              
            FacesContext.getCurrentInstance().getExternalContext().redirect("/dang-nhap.html");
        } catch (IOException ex) {
            Logger.getLogger(Sys_NguoiDungController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void onPageLoad_CheckAdmin()
    {
         if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsAdmin())
          {
              onPageLoad_DangXuat();
          }
           ReportController u = Utilities.getManagedBean(ReportController.class);
          u.setPage("/layout/Web/blankpage.xhtml");
          RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
        }
    }
     public void onPageLoad_CheckAdmin_Edit()
    {
         if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsAdmin())
          {
              onPageLoad_DangXuat();
          }
          if(findObjUser().isIsAdmin() && !findObjUser().isEditInfo())
          {
              onPageLoad_DangXuat();
          }
          ReportController u = Utilities.getManagedBean(ReportController.class);
          u.setPage("/layout/Web/blankpage.xhtml");
          RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
        }
    }
    
    public void onPageLoad_All()
    {
         if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsAdmin() && !findObjUser().isIsCP())
          {
              onPageLoad_DangXuat();
          }
          ReportController u = Utilities.getManagedBean(ReportController.class);
          u.setPage("/layout/Web/blankpage.xhtml");
          RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
        }
    }
    public void onPageLoad_All_ThongKeKhac()
    {
         if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsAdmin() && !findObjUser().isIsCP())
          {
              onPageLoad_DangXuat();
              return;
          }
          
          ReportController u = Utilities.getManagedBean(ReportController.class);
          if(findObjUser().isIsCP() && ("BIT".equals(u.getLoaiThongKe())||"BAC".equals(u.getLoaiThongKe())))
          {
              onPageLoad_DangXuat();
              return;
          }
          u.setPage("/layout/Web/blankpage.xhtml");
          RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
        }
    }
    public void onPageLoad_All_ThongKeTK()
    {
        if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsAdmin() && !findObjUser().isIsCP())
          {
              onPageLoad_DangXuat();
              return;
          }
          if(findObjUser().isIsAdmin() && !findObjUser().isThongKeTK())
          {
              onPageLoad_DangXuat();
              return;
          }
          
          ReportController u = Utilities.getManagedBean(ReportController.class);
          u.setPage("/layout/Web/blankpage.xhtml");
           RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
          //
        }     
    }
    
    public void onPageLoad_All_TKDoanhThu()
    {
        if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsAdmin() && !findObjUser().isIsCP())
          {
              onPageLoad_DangXuat();
              return;
          }
          if(findObjUser().isIsAdmin() && !findObjUser().isTkDoanhThu())
          {
              onPageLoad_DangXuat();
              return;
          }
          
          ReportController u = Utilities.getManagedBean(ReportController.class);
          u.setPage("/layout/Web/blankpage.xhtml");
          RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
        }     
    }
     public void onPageLoad_CheckCP()
    {
        if(!FacesContext.getCurrentInstance().isPostback())
        {
          if(!findObjUser().isIsCP())
          {
              onPageLoad_DangXuat();
          }
          
           ReportController u = Utilities.getManagedBean(ReportController.class);
          u.setPage("/layout/Web/blankpage.xhtml");
          RequestContext.getCurrentInstance().execute("update=\"frmCommand\"");
        }
    }
    
  
    public void onPageLoad_ChangeLanguage() throws SQLException, IOException
    {
       Utilities.setCurrentLanguage(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id").toString());
       Utilities.setLanguageData();
       FacesContext.getCurrentInstance().getExternalContext().redirect(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("url").toString());
         
    }
    
  
    public Sys_UserModel findObjUser()
    {
        HttpServletRequest httprequest=(HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession=httprequest.getSession();
        Sys_UserModel obj=(Sys_UserModel)httpsession.getAttribute(Utilities.getSS_USER());
        if(obj!=null)
        {
            return obj;
        }
        return new Sys_UserModel();
    }
    
    public static Sys_UserModel findUser()
    {
        HttpServletRequest httprequest=(HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
        HttpSession httpsession=httprequest.getSession();
        Sys_UserModel obj=(Sys_UserModel)httpsession.getAttribute(Utilities.getSS_USER());
        if(obj!=null)
        {
            return obj;
        }
        return new Sys_UserModel();
    }
     
}
